<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Android, Java">










<meta name="description" content="哈哈~">
<meta name="keywords" content="zachaxy">
<meta property="og:type" content="website">
<meta property="og:title" content="zachaxy">
<meta property="og:url" content="https://zachaxy.github.io/page/10/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="哈哈~">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="zachaxy">
<meta name="twitter:description" content="哈哈~">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/page/10/">





  <title>zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">

  <section id="posts" class="posts-expand">









  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/10/手写JVM系列-7-读取class文件/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/10/手写JVM系列-7-读取class文件/" itemprop="url">手写JVM系列(7)-读取class文件</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-10T16:21:24+08:00">
                2017-05-10
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,683
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>通过前面几节的讲解，我们已经基本了解了 class 文件的结构,每个字段代表什么含义,占多少字节,那么明确了 Class 文件的规则,接下来就可以读取 class 文件了，本节的代码均在<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">项目</a>的 classfile 包下。</p>
</blockquote>
<hr>
<h1 id="Class-文件的结构"><a href="#Class-文件的结构" class="headerlink" title="Class 文件的结构"></a>Class 文件的结构</h1><p>这里再次贴出 class 文件的结构描述：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">ClassFile &#123;</span><br><span class="line">  u4 magic;	<span class="comment">//魔数</span></span><br><span class="line">  u2 minor_version;	<span class="comment">//次版本号</span></span><br><span class="line">  u2 major_version;	<span class="comment">//主版本号</span></span><br><span class="line">  u2 constant_pool_count;	<span class="comment">//常量池大小</span></span><br><span class="line">  cp_info constant_pool[constant_pool_count-<span class="number">1</span>]; <span class="comment">//常量池</span></span><br><span class="line">  u2 access_flags;	<span class="comment">//类访问标志,表明 class 文件定义的是类还是接口，访问级别是 public 还是 private，等</span></span><br><span class="line">  u2 this_class;	<span class="comment">//</span></span><br><span class="line">  u2 super_class;	<span class="comment">//</span></span><br><span class="line">  u2 interfaces_count;	<span class="comment">//本类实现的接口数量</span></span><br><span class="line">  u2 interfaces[interfaces_count];	<span class="comment">//实现的接口,存放在数组中</span></span><br><span class="line">  u2 fields_count;		<span class="comment">//本来中含有字段数</span></span><br><span class="line">  field_info fields[fields_count];	<span class="comment">//数组中存放这各个字段</span></span><br><span class="line">  u2 methods_count;		<span class="comment">//本类中含有的方法数</span></span><br><span class="line">  method_info methods[methods_count];	<span class="comment">//数组中存放着各个方法</span></span><br><span class="line">  u2 attributes_count;			<span class="comment">//本类中含有的属性数量;</span></span><br><span class="line">  attribute_info attributes[attributes_count];	<span class="comment">//数组中存放着各个属性</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="ClassFile-类"><a href="#ClassFile-类" class="headerlink" title="ClassFile 类"></a>ClassFile 类</h1><p>根据上面的 class 结构类型，我们自己定义的类 ClassFile 也呼之欲出,每个字段和上述 class 结构几乎是一样的。类中的一个成员变量定义如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassFile</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">int</span> minorVersion;</span><br><span class="line">    <span class="keyword">int</span> majorVersion;</span><br><span class="line">    ConstantPool constantPool;</span><br><span class="line">    <span class="keyword">int</span> accessFlags;</span><br><span class="line">    <span class="keyword">int</span> thisClass;</span><br><span class="line">    <span class="keyword">int</span> superClass;</span><br><span class="line">    <span class="keyword">int</span>[] interfaces;</span><br><span class="line">    MemberInfo[] fields;</span><br><span class="line">    MemberInfo[] methods;</span><br><span class="line">    AttributeInfo[] attributes;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ClassFile</span><span class="params">(<span class="keyword">byte</span>[] classData)</span> </span>&#123;</span><br><span class="line">        ClassReader reader = <span class="keyword">new</span> ClassReader(classData);</span><br><span class="line">        read(reader);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">read</span><span class="params">(ClassReader reader)</span> </span>&#123;</span><br><span class="line">        readAndCheckMagic(reader);  <span class="comment">//验证魔数</span></span><br><span class="line">        readAndCheckVersion(reader);	<span class="comment">//校验版本</span></span><br><span class="line">        constantPool = <span class="keyword">new</span> ConstantPool(reader);	<span class="comment">//创建常量池</span></span><br><span class="line">        accessFlags = reader.readUint16();		<span class="comment">//获取类访问标志</span></span><br><span class="line">        thisClass = reader.readUint16();		<span class="comment">//</span></span><br><span class="line">        superClass = reader.readUint16();		<span class="comment">//</span></span><br><span class="line">        interfaces = reader.readUint16s();		<span class="comment">//</span></span><br><span class="line">        fields = MemberInfo.readMembers(reader, constantPool);	<span class="comment">//</span></span><br><span class="line">        methods = MemberInfo.readMembers(reader, constantPool);	<span class="comment">//</span></span><br><span class="line">        attributes = AttributeInfo.readAttributes(reader, constantPool);	<span class="comment">//</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以很清晰的看到,我们定义的 ClassFile 文件,可以看到成员变量和 JVM 中关于 class 文件的描述是一致的,只不过这里为了方便编码,统一用 int 类型来保存 u1,u2 和 u4 类型的值.</p>
<h1 id="Class-文件字节码读取辅助类"><a href="#Class-文件字节码读取辅助类" class="headerlink" title="Class 文件字节码读取辅助类"></a>Class 文件字节码读取辅助类</h1><p>接下来要解决的问题是每个字段所占的字节数不同,所以这里我们需要若干方法根据字节数读取相应的字节,所有有创建了一个<code>ClassReader</code>类,并令该类持有 class 字节码，并且在该类中保存一个 index，表明现在是从哪个字节开始读.并且提供了读取 1 字节,2 字节,4 字节,8 字节等方法,来满足<code>ClassFile</code>类中个字段对应的字节数的需求。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassReader</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">byte</span>[] data;</span><br><span class="line">    <span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ClassReader</span><span class="params">(<span class="keyword">byte</span>[] data)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.data = data;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// u1</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">byte</span> <span class="title">readUint8</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span> res = data[index++];</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// u2 这里是读取一个无符号的 16 位整,java 中没有,只能用 int 来代替吧;</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">readUint16</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span>[] res = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">2</span>];</span><br><span class="line">        res[<span class="number">0</span>] = data[index++];</span><br><span class="line">        res[<span class="number">1</span>] = data[index++];</span><br><span class="line">        <span class="keyword">return</span> ByteUtils.bytesToU16(res);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// u4</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] readUint32() &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] res = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">4</span>];</span><br><span class="line">        res[<span class="number">0</span>] = data[index++];</span><br><span class="line">        res[<span class="number">1</span>] = data[index++];</span><br><span class="line">        res[<span class="number">2</span>] = data[index++];</span><br><span class="line">        res[<span class="number">3</span>] = data[index++];</span><br><span class="line"><span class="comment">//        return ByteUtils.bytesToU32(res);  //如果需要转换的话,自行调用 ByteUtils 中的方法;</span></span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] readUint64() &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] res = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">8</span>];</span><br><span class="line">        res[<span class="number">0</span>] = data[index++];</span><br><span class="line">        res[<span class="number">1</span>] = data[index++];</span><br><span class="line">        res[<span class="number">2</span>] = data[index++];</span><br><span class="line">        res[<span class="number">3</span>] = data[index++];</span><br><span class="line">        res[<span class="number">4</span>] = data[index++];</span><br><span class="line">        res[<span class="number">5</span>] = data[index++];</span><br><span class="line">        res[<span class="number">6</span>] = data[index++];</span><br><span class="line">        res[<span class="number">7</span>] = data[index++];</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span>[] readUint16s() &#123;</span><br><span class="line">        <span class="keyword">int</span> n = readUint16();</span><br><span class="line">        <span class="keyword">int</span>[] data = <span class="keyword">new</span> <span class="keyword">int</span>[n];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            data[i] = readUint16();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> data;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] readBytes(<span class="keyword">int</span> n) &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] res = <span class="keyword">new</span> <span class="keyword">byte</span>[n];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            res[i] = data[index++];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在有了 ClassReader 这样的工具类之后,我们就可以在 ClassFile 中根据不同的字段，使用不同的 ClassReader#readXXX() 方法,来初始化成员变量,这里定义了一个 ClassFile#read() 方法来完成 ClassFile 类的初始化成员变量的任务。</p>
<h1 id="简单字段的实现"><a href="#简单字段的实现" class="headerlink" title="简单字段的实现"></a>简单字段的实现</h1><p>对于 ClassFile 的字段，除了常量和属性两个区域，其它的字段都可以很容易根据其占用的字节长度读出来，这对于编码来说并没有什么难度。在 ClassFile#read 方法中实现了所有字段的读取。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">read</span><span class="params">(ClassReader reader)</span> </span>&#123;</span><br><span class="line">    readAndCheckMagic(reader);</span><br><span class="line">    readAndCheckVersion(reader);</span><br><span class="line">    constantPool = <span class="keyword">new</span> ConstantPool(reader);</span><br><span class="line">    accessFlags = reader.readUint16();</span><br><span class="line">    thisClass = reader.readUint16();</span><br><span class="line">    superClass = reader.readUint16();</span><br><span class="line">    interfaces = reader.readUint16s();</span><br><span class="line">    fields = MemberInfo.readMembers(reader, constantPool);</span><br><span class="line">    methods = MemberInfo.readMembers(reader, constantPool);</span><br><span class="line">    attributes = AttributeInfo.readAttributes(reader, constantPool);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是对于常量和属性，因为其各自又包含了许多种类，所以需要针对不同的常量，不同的属性进行不同的读取。接下来分别介绍如何实现常量和属性的读取。</p>
<h1 id="常量的实现"><a href="#常量的实现" class="headerlink" title="常量的实现"></a>常量的实现</h1><p>这里需要定义一个常量的抽象类 ConstantInfo，表示一个常量 item，具体的常量由其子类实现，这里对外提供一个统一的接口来根据不同的 tag，创建不同的具体常量实现类，以完成常量池的初始化。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> ConstantInfo <span class="title">create</span><span class="params">(<span class="keyword">int</span> tag, ConstantPool constantPool)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (tag) &#123;</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Integer:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantIntegerInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Float:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantFloatInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Long:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantLongInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Double:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantDoubleInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Utf8:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantUtf8Info();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_String:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantStringInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Class:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantClassInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Fieldref:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMemberRefInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Methodref:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMemberRefInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_InterfaceMethodref:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMemberRefInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_NameAndType:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantNameAndTypeInfo();</span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span> 2017/5/3 0003 下面三个类还未编码; </span></span><br><span class="line">        <span class="keyword">case</span> CONSTANT_MethodType:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMethodTypeInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_MethodHandle:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMethodHandleInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_InvokeDynamic:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantInvokeDynamicInfo();</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"java.lang.ClassFormatError: constant pool tag!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>并且提供一个抽象方法，供子类实现，因为每种常量所占的字节数并不相同。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">readInfo</span><span class="params">(ClassReader reader)</span></span></span><br></pre></td></tr></table></figure>

<p>而对于各自具体的常量，需要根据各自常量的结构来读取，其结构已经在<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-5-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B8%B8%E9%87%8F%E6%B1%A0/">手写 JVM 系列(5)-分析 class 文件-常量池</a>中进行了详细的介绍。具体实现请参照<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">项目源码</a></p>
<h1 id="常量池的实现"><a href="#常量池的实现" class="headerlink" title="常量池的实现"></a>常量池的实现</h1><p>有了上面各个常量的具体实现，那么接下来我们就可以构建常量池了。常量池其实就是本 class 文件中所有常量的集合。</p>
<p>因为常量池是根据索引来访问的，因此我们也很自然的想到用数组来表示常量池，数组类型是上面定义的常量类型，注意索引从 1 开始，0 是无效索引。常量池的初始化时在构造方法中，通过 ConstantInfo 提供的 readConstantInfo 静态方法，读取一字节 tag，根据 tag 创建不同的常量实现类，并添加到常量池数组中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RuntimeConstantPool</span> </span>&#123;</span><br><span class="line">    ConstantInfo[] infos;  <span class="comment">//保存类文件常量池中的所有常量,常量分为多种类型,基本类型都有对应的常量,以及字符串等;(简言之,这就是常量池的抽象)</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> constantPoolCount; <span class="comment">//class 文件中常量池中的常量数量</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ConstantPool</span><span class="params">(ClassReader reader)</span> </span>&#123;</span><br><span class="line">        <span class="comment">/*读出常量池的大小;接下来根据这个大小,生成常量信息数组;</span></span><br><span class="line"><span class="comment">        注意:</span></span><br><span class="line"><span class="comment">        1. 表头给出的常量池大小比实际大 1,所以这样的话,虽然可能生成了这么大的,但是 0 不使用,直接从 1 开始;</span></span><br><span class="line"><span class="comment">        2. 有效的常量池索引是 1~n–1。0 是无效索引，表示不指向任何常量</span></span><br><span class="line"><span class="comment">        3. CONSTANT_Long_info 和 CONSTANT_Double_info 各占两个位置。</span></span><br><span class="line"><span class="comment">           也就是说，如果常量池中存在这两种常量，实际的常量数量比 n–1 还要少，而且 1~n–1 的某些数也会变成无效索引。</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">        constantPoolCount = reader.readUint16();</span><br><span class="line">        infos = <span class="keyword">new</span> ConstantInfo[constantPoolCount];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; constantPoolCount; i++) &#123;</span><br><span class="line">            infos[i] = ConstantInfo.readConstantInfo(reader, <span class="keyword">this</span>);</span><br><span class="line">            <span class="keyword">if</span> ((infos[i] <span class="keyword">instanceof</span> ConstantLongInfo) || (infos[i] <span class="keyword">instanceof</span> ConstantDoubleInfo)) &#123;</span><br><span class="line">                i++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">  ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="属性的实现"><a href="#属性的实现" class="headerlink" title="属性的实现"></a>属性的实现</h1><p>对于属性的编码，和常量池的编码思路是相似的，其实这里称为“属性池”更为贴切。因为他是各种属性的集合。而 class 文件本身，方法表集合和字段表集合中均持有属性表。</p>
<p>同样，提供一个抽象类来表示一个属性，其定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AttributeInfo</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">readInfo</span><span class="params">(ClassReader reader)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//读取单个属性</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> AttributeInfo <span class="title">readAttribute</span><span class="params">(ClassReader reader, ConstantPool constantPool)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> attrNameIndex = reader.readUint16();</span><br><span class="line">        String attrName = constantPool.getUtf8(attrNameIndex);</span><br><span class="line">        <span class="keyword">int</span> attrLen = ByteUtils.byteToInt32(reader.readUint32());</span><br><span class="line">        AttributeInfo attrInfo = create(attrName, attrLen, constantPool);</span><br><span class="line">        attrInfo.readInfo(reader);</span><br><span class="line">        <span class="keyword">return</span> attrInfo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//读取属性表;这个和 ConstantPool 中的方法类似,一般都是一下全部读取出来,不会只读一个</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> AttributeInfo[] readAttributes(ClassReader reader, ConstantPool constantPool) &#123;</span><br><span class="line">        <span class="keyword">int</span> attributesCount = reader.readUint16();</span><br><span class="line">        AttributeInfo[] attributes = <span class="keyword">new</span> AttributeInfo[attributesCount];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; attributesCount; i++) &#123;</span><br><span class="line">            attributes[i] = readAttribute(reader, constantPool);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> attributes;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//Java 虚拟机规范预定义了 23 种属性，先解析其中的 8 种</span></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    23 种预定义属性可以分为三组。</span></span><br><span class="line"><span class="comment">    第一组属性是实现 Java 虚拟机所必需的，共有 5 种；</span></span><br><span class="line"><span class="comment">    第二组属性是 Java 类库所必需的，共有 12 种；</span></span><br><span class="line"><span class="comment">    第三组属性主要提供给工具使用，共有 6 种。第三组属性是可选的，也就是说可以不出现在 class 文件中。</span></span><br><span class="line"><span class="comment">    (如果 class 文件中存在第三组属性，Java 虚拟机实现或者 Java 类库也是可以利用它们的，比如使用 LineNumberTable 属性在异常堆栈中显示行号。)</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> AttributeInfo <span class="title">create</span><span class="params">(String attrName, <span class="keyword">int</span> attrLen, ConstantPool constantPool)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (attrName.equals(<span class="string">"Code"</span>)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> CodeAttribute(constantPool);</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"ConstantValue"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantValueAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"Deprecated"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> DeprecatedAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"Exceptions"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ExceptionsAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"LineNumberTable"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> LineNumberTableAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"LocalVariableTable"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> LocalVariableTableAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"SourceFile"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> SourceFileAttribute(constantPool);</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"Synthetic"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> SyntheticAttribute();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> UnparsedAttribute(attrName, attrLen);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其内部定义了抽象方法 readInfo，供各具体的属性类去读取相应的数据。而对外，提供了一个 readAttributes 的方法，来返回当前 方法表集合或者字段表集合中的的属性集合。与常量池不同的是：常量是根据不同的 tag（代表一个整数）来区分不同的常量，而属性是根据不同的 name（字符串）来区分不同的属性，所以创建属性的方法 AttributeInfo#create 方法。</p>
<p>而对于各自具体的属性，需要根据各自属性的结构来读取，其结构已经在<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-6-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B1%9E%E6%80%A7%E8%A1%A8/">手写 JVM 系列(6)-分析 class 文件-属性表</a>中进行了详细的介绍。具体实现请参照<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">项目源码</a></p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/09/手写JVM系列-6-分析class文件-属性表/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/09/手写JVM系列-6-分析class文件-属性表/" itemprop="url">手写JVM系列(6)-分析class文件-属性表</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-09T16:24:05+08:00">
                2017-05-09
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,528
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>和常量池类似，各种属性表达的信息也各不相同，因此无法用统一的结构来定义。不同之处在于，常量是由 Java 虚拟机规范严格定义的，共有 14 种。但属性是可以扩展的，不同的虚拟机实现可以定义自己的属性类型。由于这个原因，Java 虚拟机规范没有使用 tag，而是使用<strong>属性名</strong>来区别不同的属性。属性数据放在属性名之后的 u1 表中，这样 Java 虚拟机实现就可以跳过自己无法识别的属性。</p>
</blockquote>
<h1 id="属性的基本结构"><a href="#属性的基本结构" class="headerlink" title="属性的基本结构"></a>属性的基本结构</h1><p>属性的结构定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">attribute_info &#123;</span><br><span class="line">  u2 attribute_name_index;</span><br><span class="line">  u4 attribute_length;</span><br><span class="line">  u1 info[attribute_length];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第一个字段是属性名在常量池的索引，指向常量池中的 CONSTANT_Utf8_info 常量。</p>
<p>第二个字段是后面跟着的属性字节码的长度，用 u4 表示，表明属性的大小最大可以为 2^32-1。</p>
<p>第三个字段就是属性字节码。</p>
<h1 id="属性的种类"><a href="#属性的种类" class="headerlink" title="属性的种类"></a>属性的种类</h1><p>按照用途，有 23 种预定义属性，可以分为三组。</p>
<ol>
<li>第一组属性是实现 Java 虚拟机所必需的，共有 5 种；</li>
<li>第二组属性是 Java 类库所必需的，共有 12 种；</li>
<li>第三组属性主要提供给工具使用，共有 6 种。（这组属性是可选的，也就是说可以不出现在 class 文件中。如果 class 文件中存在第三组属性，Java 虚拟机实现或者 Java 类库也是可以利用它们的，比如使用 LineNumberTable 属性在异常堆栈中显示行号。）</li>
</ol>
<p>这里只介绍几个常用的属性：</p>
<table>
<thead>
<tr>
<th>属性名</th>
<th>位置</th>
<th>含义</th>
<th>分组</th>
</tr>
</thead>
<tbody><tr>
<td>Deprecated</td>
<td>ClassFile, field_info, method_info</td>
<td>被声明为 deprecated 的方法和字段</td>
<td>3</td>
</tr>
<tr>
<td>Synthetic</td>
<td>ClassFile, field_info, method_info</td>
<td>标示方法或字段是由编译器自动生成的</td>
<td>2</td>
</tr>
<tr>
<td>SourceFile</td>
<td>ClassFile</td>
<td>记录源文件的名称</td>
<td>3</td>
</tr>
<tr>
<td>ConstantValue</td>
<td>field_info</td>
<td>final 关键字定义的常量值</td>
<td>1</td>
</tr>
<tr>
<td>Code</td>
<td>method_info</td>
<td>Java 代码编译成的字节码指令</td>
<td>1</td>
</tr>
<tr>
<td>Exceptions</td>
<td>method_info</td>
<td>方法抛出的异常</td>
<td>1</td>
</tr>
<tr>
<td>LineNumberTable</td>
<td>Code</td>
<td>Java 源代码的行号与字节码指令的对应关系</td>
<td>3</td>
</tr>
<tr>
<td>LocalVariableTable</td>
<td>Code</td>
<td>方法的局部变量描述</td>
<td>3</td>
</tr>
</tbody></table>
<h1 id="属性的具体介绍"><a href="#属性的具体介绍" class="headerlink" title="属性的具体介绍"></a>属性的具体介绍</h1><p>由于属性种类较多，这里只选几个有代表性的属性进行讲解。</p>
<h2 id="Deprecated"><a href="#Deprecated" class="headerlink" title="Deprecated"></a>Deprecated</h2><p>最简单的属性，仅起标记作用，不包含任何数据。Deprecated 属性用于指出类、接口、字段或方法已经不建议使用，编译器等工具可以根据 Deprecated 属性输出警告信息。J2SE 5.0 之前可以使用 Javadoc 提供的@deprecated 标签指示编译器给类、接口、字段或方法添加 Deprecated 属性。其结构定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Deprecated_attribute &#123;</span><br><span class="line">  u2 attribute_name_index;</span><br><span class="line">  u4 attribute_length;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于不包含任何数据，所以 attribute_length 的值必须是 0。自然也就没有了后面的 info 数组字段了。</p>
<h2 id="Synthetic"><a href="#Synthetic" class="headerlink" title="Synthetic"></a>Synthetic</h2><p>最简单的属性，仅起标记作用，不包含任何数据。Synthetic 属性用来标记源文件中不存在、由编译器生成的类成员，引入 Synthetic 属性主要是为了支持嵌套类和嵌套接口。其结构定义如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Synthetic_attribute &#123;</span><br><span class="line">  u2 attribute_name_index;</span><br><span class="line">  u4 attribute_length;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于不包含任何数据，所以 attribute_length 的值必须是 0。自然也就没有了后面的 info 数组字段了。</p>
<h3 id="桥接方法"><a href="#桥接方法" class="headerlink" title="桥接方法"></a>桥接方法</h3><p>这里要说一下，哪些方法是我们在代码里没有写，但是字节码文件会给我们加上呢? 首先构造方法，如果我们默认不写，那么字节码会自动添加上的。还有就是泛型，这里详细说明一下。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">A</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">abstract</span> T <span class="title">get</span><span class="params">(T t)</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span>&lt;<span class="title">String</span>&gt; </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function">String <span class="title">get</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestBridge</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Class&lt;B&gt; clazz = B.class;</span><br><span class="line">        Method[] methods = clazz.getDeclaredMethods();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; methods.length; i++) &#123;</span><br><span class="line">            Method m = methods[i];</span><br><span class="line">            System.out.println(getMethodInfo(m) + <span class="string">" is Bridge Method? "</span> + m.isBridge());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getMethodInfo</span><span class="params">(Method m)</span></span>&#123;</span><br><span class="line">        StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        sb.append(m.getReturnType()).append(<span class="string">" "</span>);</span><br><span class="line">        sb.append(m.getName());</span><br><span class="line">        Class[]params = m.getParameterTypes();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; params.length; i++) &#123;</span><br><span class="line">            sb.append(params[i].getName()).append(<span class="string">" "</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sb.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>B 中复写了 A 中的 get 方法，那么在 main 方法中，打印 B 中的方法数，应该就是一个吧，那接下来看一下打印结果：</p>
<blockquote>
<p>[class java.lang.String get] is Bridge Method? false</p>
<p>[class java.lang.Object get] is Bridge Method? true </p>
</blockquote>
<p>会不会感到诧异，怎么会多出一个返回值为 Object 的 get 方法？</p>
<p>这个是 java5 中的泛型所带来的结果了。针对上面的这段代码分析下：<br>在 java5 之前，你可以往一个集合里扔任何你想扔的对象。但是从集合中取对象却变得很难。你不知道你下个取到的对象将会是什么具体类型的。因为取出来的对象是 Object 类型的，不知道转成什么类型，所以只能使用所有 Object 的方法了，这样就毫无意义了。所以在 java5 中提供了泛型这一新特性。我们在写代码的时候可以指定集合可以存放对象的类型。然后<strong>将类型检查的事情交给编译器去做</strong>，减少了程序员的工作。<br>​    </p>
<p>上面代码中&lt;&gt;中的 T 和 String 就是指定类的参数类型。T 代表一种泛型，告诉编译器，一旦有类指定了 T 这个参数的实际类，那么 get 方法返回的类型也必须为同一个类（当然也可以是这个类的子类；这个也是 java5 中的协变式返回新特性），如果不是，就必须报错提示；将原来的运行时可能出现的错误提前到编译期了。那么，假设你是 java5 编译器的设计者，你会如何来设计让编译器能实现这个特性，同时能保证编译出来的字节码可以在老版本的 jdk 中运行呢？java5 编译器中作了个很巧妙的设计——桥接方法。 </p>
<p>那么编译器是如何编译这个抽象类 A 的呢？</p>
<p>对于 A：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">A</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">abstract</span> T <span class="title">get</span><span class="params">(T t)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>编译器会直接将其转换为下面的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">A</span>&lt;<span class="title">Object</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">abstract</span> Object <span class="title">get</span><span class="params">(Object t)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面这个过程称为类型擦除，将泛型类型参数全部替换为 Object。</p>
<p>对于 B 类，它继承了 A 类，指定了 T 参数为 String。如果还按照以前那么编译，那编译的类就是： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">    <span class="function">String <span class="title">get</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样在运行时肯定会报错，因为 B 继承了 A，而 A 又是 asbtract 类，B 还没 overriding A 中 Object get()方法。如何解决这个错误呢？java5 编译器在编译的时候做了些手脚。当编译器发现你指定了类型参数，便会在编译的字节码中添加一个桥接方法。所以代码变成了下面这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">    <span class="comment">//这个就是编译器添加的方法</span></span><br><span class="line">    <span class="function">Object <span class="title">get</span><span class="params">(Object s)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (Object) get((String) s);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function">String <span class="title">get</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而我们实际在调用 B 的 get 方法时，调用的其实是第二个方法，因为我们的参数传入的是 String。而如果是使用了多态，调用了 A.get,那么调用的将是 B 的第一个 get 方法。</p>
<ul>
<li><p>第一个 get 方法的描述符是：(Ljava/lang/Object;)Ljava/lang/Object;</p>
<p>access_flag:0x0001(public)</p>
</li>
<li><p>第二个 get 方法的描述符是：(Ljava/lang/String;)Ljava/lang/String;</p>
<p>access_flag:0x1041(public Synthetic bridge)</p>
</li>
</ul>
<h2 id="SourceFile"><a href="#SourceFile" class="headerlink" title="SourceFile"></a>SourceFile</h2><p>SourceFile 是可选定长属性，只会出现在 ClassFile 结构中，用于指出源文件名。其结构定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SourceFile_attribute &#123;</span><br><span class="line">  u2 attribute_name_index;</span><br><span class="line">  u4 attribute_length;</span><br><span class="line">  u2 sourcefile_index;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>attribute_length 的值必须是 2。因为这个长度就是下面一个字段 sourcefile_index 的长度，这个索引是常量池的索引，常量池长度是用 u2 来表示的，所以该索引决不能超出 u2 的最大值，因此最大用两字节表示，所以 attribute_length 值固定为 2。</p>
<p>sourcefile_index 是常量池索引，指向<code>CONSTANT_Utf8_info</code>常量。而<code>CONSTANT_Utf8_info</code>中的字符串就是当前源文件的文件名。</p>
<h2 id="ConstantValue"><a href="#ConstantValue" class="headerlink" title="ConstantValue"></a>ConstantValue</h2><p>ConstantValue 是定长属性，只会出现在 field_info 结构中，用于表示常量表达式的值。其作用是通知虚拟机自动为静态变量赋值。只有被 static 修饰的变量（类变量）才可以使用这项属性。</p>
<p>其结构定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ConstantValue_attribute &#123;</span><br><span class="line">    u2 attribute_name_index;</span><br><span class="line">    u4 attribute_length;</span><br><span class="line">    u2 constantvalue_index;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>下面有三种情况：</p>
<ul>
<li>int a1 = 123；</li>
<li>static int a2 = 123;</li>
<li>final static int a3 = 123</li>
</ul>
<p>对于非 static 变量，eg：a1，其赋值是在实例构造器<code>&lt;init&gt;</code>方法中完成的。</p>
<p>而对于 static 变量，eg：a2，a3，有两种赋值方式。</p>
<ol>
<li>在类构造器<code>&lt;clinit&gt;</code>方法中。</li>
<li>使用 ConstantValue 属性。</li>
</ol>
<p>目前 Sun Javac 的选择是：前提都是针对于用 static 修饰的静态变量。如果是用 final static 修饰的话，并且这个变量是基本类型或者 String，那么使用 2 赋值。否则使用 1 赋值。</p>
<p>因此这里的 constantvalue_index 是指向常量池中一个字面量类别（CONSTANT_Integer、CONSTANT_Float、CONSTANT_Long、CONSTANT_Double、CONSTANT_Utf8 五种中的一种）的索引，该常量中保存着变量的值。</p>
<h2 id="Code"><a href="#Code" class="headerlink" title="Code"></a>Code</h2><p>Code 是变长属性，只存在于 method_info 结构中。Code 属性中存放字节码等方法相关信息。其结构定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Code_attribute &#123;</span><br><span class="line">    u2 attribute_name_index;</span><br><span class="line">    u4 attribute_length;</span><br><span class="line">    u2 max_stack;</span><br><span class="line">    u2 max_locals;</span><br><span class="line">    u4 code_length;</span><br><span class="line">    u1 code[code_length];</span><br><span class="line">    u2 exception_table_length;</span><br><span class="line">    exception_table[exception_table_length];</span><br><span class="line">    u2 attributes_count;</span><br><span class="line">    attribute_info attributes[attributes_count];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>关于上面的 exception_table，其结构定义如下。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123; </span><br><span class="line">  	u2 start_pc;</span><br><span class="line">    u2 end_pc;</span><br><span class="line">    u2 handler_pc;</span><br><span class="line">    u2 catch_type;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>java 方法中的代码经过 Javac 编译器处理之后，最终变成<strong>字节码指令</strong>存储在 Code 属性内。Code 属性出现在方法表的属性集合之中，但是并非所有的方法都必须存在 Code 这个属性。譬如接口或者抽象类中的方法就不存在 Code 属性。</p>
<p>接下来对其中的字段做一个介绍：</p>
<ul>
<li>attribute_name_index：指向 CONSTANT_Utf8_info 类型常量的索引，这个常量值固定为“Code”，代表了该属性的属性名称。</li>
<li>attribute_length：代表该属性的长度，包括从 attribute_name_index 开始到 attributes[]数组结束。</li>
<li>max_stack：代表操作数栈的深度的最大值。在方法执行的任意时刻，操作数栈都不能超过这个深度。</li>
<li>max_locals：代表了局部变量表所需的存储空间大小。在这里 max_locals 的单位是 Slot，Slot 是虚拟机为局部变量非配内存所使用的最小单位。对于 byte、char、short、int、float、boolean、returnAddress 等长度不超过 32 位的数据，每个局部变量占用一个 Slot，而 double 和 long 这种 64 位的数据则需要两个 Slot 来存放。</li>
<li>code_length：指示下面的 code 字节码数组的长度。虽然这是一个 u4 类型，理论上最大值可以达到 2^32-1，但是 Java 虚拟机明确规定一个方法中的指令不能超过 65535 条字节码指令，也就是说它实际是使用了 u2 的长度。</li>
<li>code[code_length]：存放的是 Java 源程序编译后生成的 <strong>字节码指令</strong> ，关于字节码指令，会在<a href="https://zachaxy.github.io/2017/05/13/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-9-%E6%8C%87%E4%BB%A4%E9%9B%86/">手写JVM系列(9)-指令集</a>一节详细说明。</li>
<li>exception_table_length：指示下面的异常表数组的长度。</li>
<li>exception_table[exception_table_length] 关于异常处理，会在<a href>后面的文章</a>中进行详细说明。</li>
<li>attributes_count：指示下面的属性表数组的长度。</li>
<li>attribute_info attributes[attributes_count]：Code 本身就已经是属性了，在这个属性的字段中还包括一些其它的属性…那么就存在这个表中。</li>
</ul>
<h3 id="关于-max-locals"><a href="#关于-max-locals" class="headerlink" title="关于 max_locals"></a>关于 max_locals</h3><p>max_locals 给出局部变量表大小。在这里 max_locals 的单位是 Slot，Slot 是虚拟机为局部变量非配内存所使用的最小单位。对于 byte、char、short、int、float、boolean、returnAddress 等长度不超过 32 位的数据，每个局部变量占用一个 Slot，而 double 和 long 这种 64 位的数据则需要两个 Slot 来存放。</p>
<p>局部变量表中存放的内容</p>
<ul>
<li>方法参数（包括实例方法中隐藏参数 this）</li>
<li>显式异常处理器的参数（catch 块所定义的异常）</li>
<li>方法体中递归的局部变量</li>
</ul>
<p>但是这里要注意的是：并非在方法中用到了多少个局部变量，就把这些局部变量所占的 Slot 的数量作为 max_locals 的值，因为局部变量表中的 Slot 是可以重用的，当代码执行超出了某一局部变量的<strong>作用域</strong>之后，这个 Slot 就可以被其它局部变量所使用了，所以 Javac 编译器会根据变量的作用域来分配 Slot 给各个变量使用，然后计算出 max_locals 的大小。</p>
<p><strong>方法体内部使用的 this 从何而来？</strong></p>
<p>大家注意到没有，定义在类中的非静态方法内部，可以使用 this 来访问当前的对象内的属性，它的实现方法是在 Javac 编译的时候把 this 添加到每个非静态方法的方法参数中，所以在方法内访问的 this 其实是本方法的参数。我们自己定义一个<code>void func()</code>的方法，使用 javap 命令查看其 Code 字节码，会发现这个 func 方法的<code>Args_size=1</code>,原因就在这，这个参数就是编译器默认为我们添加进去的<code>this</code></p>
<h2 id="Exception"><a href="#Exception" class="headerlink" title="Exception"></a>Exception</h2><p>这里将的 Exception 属性和 Code 属性是一级的。并不是 Code 属性中的异常属性表。</p>
<p>这里的 Exception 属性的作用是列举方法中通过<code>throws</code>关键字后面列举的异常。其结构如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Exceptions_attribute &#123;</span><br><span class="line">    u2 attribute_name_index;</span><br><span class="line">    u4 attribute_length;</span><br><span class="line">    u2 number_of_exceptions;</span><br><span class="line">    u2 exception_index_table[number_of_exceptions];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里的 number_of_exceptions 项表示方法可能抛出的异常的数量。后面跟的是一个 exception_index_table，该数组中每个元素的长度均为 u2，因为该数组中保存的是一个指向常量池中 CONSTANT_Class_info 型的常量的索引，代表该异常的类型。</p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/09/手写JVM系列-5-分析class文件-常量池/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/09/手写JVM系列-5-分析class文件-常量池/" itemprop="url">手写JVM系列(5)-分析class文件-常量池</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-09T10:30:01+08:00">
                2017-05-09
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,536
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>常量池占据了 class 文件很大一部分数据，里面存放着各式各样的常量信息，包括数字和字符串常量、类和接口名、字段和方法名等。本节将详细介绍常量池和各种常量。</p>
</blockquote>
<h1 id="常量池在-class-文件中格式"><a href="#常量池在-class-文件中格式" class="headerlink" title="常量池在 class 文件中格式"></a>常量池在 class 文件中格式</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ClassFile &#123;</span><br><span class="line">  ...</span><br><span class="line">  u2 constant_pool_count;	<span class="comment">//常量池大小</span></span><br><span class="line">  cp_info constant_pool[constant_pool_count-<span class="number">1</span>]; <span class="comment">//常量池</span></span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>首先读出常量池的大小，这是一个 u2 类型的数据，因此，这也表明了常量池最大为 2^16-1，如果你不是故意为难虚拟机，将工程中所有的代码都写到一个 class 文件中，相信这已经足够用了。</p>
<p>接下来根据这个大小,生成常量信息数组，注意：</p>
<ol>
<li>表头给出的常量池大小比实际大 1,所以这样的话,虽然可能生成了这么大的,但是 0 不使用,直接从 1 开始;</li>
<li>有效的常量池索引是 1~n–1。0 是无效索引，表示不指向任何常量</li>
<li>CONSTANT_Long_info 和 CONSTANT_Double_info 各占两个位置。也就是说，如果常量池中存在这两种常量，实际的常量数量比 n–1 还要少，这也导致了 1~n–1 的某些数也会变成无效索引。</li>
</ol>
<h1 id="常量池分类"><a href="#常量池分类" class="headerlink" title="常量池分类"></a>常量池分类</h1><p>常量池中的常量分为两类：字面量 和 符号引用</p>
<ul>
<li><p>字面量:文本字符串,声明为 final 的常量值等</p>
<ul>
<li><p>数字常量</p>
</li>
<li><p>字符串常量</p>
<p>​</p>
</li>
</ul>
</li>
<li><p>符号引用:Javac 在编译的时候,没有像 c 语言那样的”连接”这一步,而是在加载 class 文件的时候动态加载,拿到该符号引用指向的字符串,再使用反射,加载相应的类.</p>
<ul>
<li>类</li>
<li>接口</li>
<li>字段</li>
<li>方法</li>
</ul>
</li>
</ul>
<p>字面量是可以直接获取到其值的,而符号引用是通过索引直接或者间接指向 CONSTANT_Utf8_info 常量,然后拿到其字面量的;</p>
<h1 id="常量池具体类型"><a href="#常量池具体类型" class="headerlink" title="常量池具体类型"></a>常量池具体类型</h1><p>常量池具体可以分为以下 14 中类型，其基本结构都是由一个 u1 的 tag，后面跟一个具体类型的数据组成。</p>
<p><img src="http://oi8e3sh89.bkt.clouddn.com/image/jvm/%E5%B8%B8%E9%87%8F%E6%B1%A0%E4%B8%AD%E5%B8%B8%E9%87%8F%E9%A1%B9%E7%BB%93%E6%9E%84%E8%A1%A8.png" alt="常量池中的 14 种常量项的结构总表"></p>
<p>按照常量池的分类一节，将这 14 中分为两类</p>
<ul>
<li>字面量：<ul>
<li>CONSTANT_Integer</li>
<li>CONSTANT_Float</li>
<li>CONSTANT_Long</li>
<li>CONSTANT_Double</li>
<li>CONSTANT_Utf8</li>
</ul>
</li>
<li>符号引用：剩余的 10 种。</li>
</ul>
<p>下面分别从字面量大类和符号引用大类中各选两个有代表性的常量进行讲解。</p>
<h2 id="CONSTANT-Integer"><a href="#CONSTANT-Integer" class="headerlink" title="CONSTANT_Integer"></a>CONSTANT_Integer</h2><p>CONSTANT_Integer_info 使用 4 字节存储整数常量，其结构定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CONSTANT_Integer_info &#123;</span><br><span class="line">  u1 tag;</span><br><span class="line">  u4 bytes;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因此我们在读到 tag 为 CONSTANT_Integer 时，接下来需要读取 4 字节的数据，从而拼接成这一个整数。</p>
<p>float，long，double 和 int 是类似的，读到对应的 tag，分别去读 4,8,8 字节的数据拼接起来，就是实际的数值。</p>
<h2 id="CONSTANT-Utf8"><a href="#CONSTANT-Utf8" class="headerlink" title="CONSTANT_Utf8"></a>CONSTANT_Utf8</h2><p>CONSTANT_Utf8 类型代表的是常量池中真正的字符串，其结构定义如下，读取到对应的 tag 后，后面是一个 u2 的数据，表明字符串的长度 len，接下来是长度为 len 的字节，代表真正的字符串。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CONSTANT_Utf8_info &#123;</span><br><span class="line">  u1 tag;</span><br><span class="line">  u2 length;</span><br><span class="line">  u1 bytes[length];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是这里要注意的是，字符串在 class 文件中是以 MUTF-8（Modified UTF-8）方式编码的。MUTF-8 编码方式和 UTF-8 大致相同，但并不兼容。<br>差别有两点：一是 null 字符（代码点 U+0000）会被编码成 2 字节：0xC0、0x80；二是补充字符（Supplementary Characters，代码点大于U+FFFF 的 Unicode 字符）是按 UTF-16 拆分为代理对（Surrogate Pair）分别编码的。具体转换方法请看<a href="https://github.com/zachaxy/JVM/blob/master/Java/src/classfile/ConstantUtf8Info.java" target="_blank" rel="noopener">源码</a>，这里的转换方法是直接根据 java.io.DataInputStream.readUTF（）方法改写的。将读到的 byte 数组经过转码之后得到其代表的具体字符串。</p>
<p>常量类型中有一个 ConstantStringInfo，这个常量的名字迷惑性比较强，但是它里面并没有保存真正的字符串，而是保存了一个指向常量池中的索引，这个索引对应的常量类型一定是 CONSTANT_Utf8，这个常量中的字符串才是 ConstantStringInfo 中想表达的字符串。</p>
<h2 id="CONSTANT-Class"><a href="#CONSTANT-Class" class="headerlink" title="CONSTANT_Class"></a>CONSTANT_Class</h2><p>CONSTANT_Class_info 常量表示类或者接口的符号引用，指向是接口或者类名。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">CONSTANT_Class_info &#123;</span><br><span class="line">  u1 tag;</span><br><span class="line">  u2 name_index;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其 name_index 是常量池索引，指向 <code>CONSTANT_Utf8_info</code> 常量。所以如果想真正的拿到当前 class 的全限定名，需要通过 name_index 先得到常量池中的 <code>CONSTANT_Utf8_info</code>，然后在获取其中的值。</p>
<h2 id="CONSTANT-NameAndType"><a href="#CONSTANT-NameAndType" class="headerlink" title="CONSTANT_NameAndType"></a>CONSTANT_NameAndType</h2><p>CONSTANT_NameAndType_info 给出字段或方法的名称和描述符。CONSTANT_Class_info 和 CONSTANT_NameAndType_info 加在一起可以唯一确定一个字段或者方法。其结构如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CONSTANT_NameAndType_info &#123;</span><br><span class="line">  u1 tag;</span><br><span class="line">  u2 name_index;</span><br><span class="line">  u2 descriptor_index;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>字段或方法名由 name_index 给出，字段或方法的描述符由 descriptor_index 给出。name_index 和 descriptor_index 都是常量池索引，指向 CONSTANT_Utf8_info 常量。字段和方法名就是代码中出现的（或者编译器生成的）字段或方法的名字。</p>
<p>Java 虚拟机规范定义了一种简单的语法来描述字段和方法，可以根据下面的规则生成描述符。</p>
<ol>
<li><p>类型描述符。</p>
<ul>
<li>基本类型 byte、short、char、int、long、float 和 double 的描述符是单个字母，分别对应 B、S、C、I、J、F 和 D。注意，long 的描述符是 J 而不是 L。</li>
<li>引用类型的描述符是“L＋类的完全限定名＋分号”</li>
<li>数组类型的描述符是“[＋数组元素类型描述符”</li>
</ul>
</li>
<li><p>字段描述符就是字段的类型描述符。</p>
</li>
<li><p>方法描述符格式是：“（按参数顺序的参数类型描述符）+返回值类型描述符”，其中 void 返回值由单个字母 V 表示。</p>
</li>
</ol>
<h1 id="常量池类型总结"><a href="#常量池类型总结" class="headerlink" title="常量池类型总结"></a>常量池类型总结</h1><p>可以把常量池中的常量分为两类：字面量（literal）和符号引用（symbolic reference）。字面量包括数字常量和字符串常量，符号引用包括类和接口名、字段和方法信息等。除了字面量，其他常量都是通过索引指向 CONSTANT_Utf8_info 常量来获取其对应的字符串。</p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/09/手写JVM系列-4-分析class文件/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/09/手写JVM系列-4-分析class文件/" itemprop="url">手写JVM系列(4)-分析class文件</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-09T09:49:14+08:00">
                2017-05-09
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,155
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <blockquote>
<p>前面一节已经介绍了如何获取了字节文件的字节流,那么在获取到字节流之后,就要读取并解析字节码了,这一节会介绍 class 文件的结构.本节的代码均在<strong>classfile包</strong>下,源码<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">在这里</a></p>
</blockquote>
<h1 id="class文件的基本结构"><a href="#class文件的基本结构" class="headerlink" title="class文件的基本结构"></a>class文件的基本结构</h1><p>构成 class 文件的基本数据单位是字节，可以把整个 class 文件当成一个字节流来处理。稍大一些的数据由连续多个字节构成，这些数据在class文件中以<strong>大端（big-endian）方式存储</strong>。为了描述class文件格式，Java虚拟机规范定义了<code>u1</code>、<code>u2</code>和<code>u4</code>三种数据类型来表示1、2和4字节<strong>无符号整数</strong></p>
<p>class文件中相同类型的多条数据一般按表（table）的形式存储（包括接下来要讲的常量池，属性表，接口索引集合，字段表集合，方法表集合）,表由表头和表项（item）构成，表头是 u2 或 u4 整数。假设表头是 n，后面就紧跟着 n 个表项数据。</p>
<p>class文件的结构描述:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">ClassFile &#123;</span><br><span class="line">  u4 magic;	<span class="comment">//魔数</span></span><br><span class="line">  u2 minor_version;	<span class="comment">//次版本号</span></span><br><span class="line">  u2 major_version;	<span class="comment">//主版本号</span></span><br><span class="line">  u2 constant_pool_count;	<span class="comment">//常量池大小</span></span><br><span class="line">  cp_info constant_pool[constant_pool_count-<span class="number">1</span>]; <span class="comment">//常量池</span></span><br><span class="line">  u2 access_flags;	<span class="comment">//类访问标志,表明class文件定义的是类还是接口，访问级别是public还是private，等</span></span><br><span class="line">  u2 this_class;	<span class="comment">//</span></span><br><span class="line">  u2 super_class;	<span class="comment">//</span></span><br><span class="line">  u2 interfaces_count;	<span class="comment">//本类实现的接口数量</span></span><br><span class="line">  u2 interfaces[interfaces_count];	<span class="comment">//实现的接口,存放在数组中</span></span><br><span class="line">  u2 fields_count;		<span class="comment">//本来中含有字段数</span></span><br><span class="line">  field_info fields[fields_count];	<span class="comment">//数组中存放这各个字段</span></span><br><span class="line">  u2 methods_count;		<span class="comment">//本类中含有的方法数</span></span><br><span class="line">  method_info methods[methods_count];	<span class="comment">//数组中存放着各个方法</span></span><br><span class="line">  u2 attributes_count;			<span class="comment">//本类中含有的属性数量;</span></span><br><span class="line">  attribute_info attributes[attributes_count];	<span class="comment">//数组中存放着各个属性</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="解读-class-文件"><a href="#解读-class-文件" class="headerlink" title="解读 class 文件"></a>解读 class 文件</h1><p>接下来依次对 class 文件中的各个字段做一个介绍:</p>
<h2 id="魔数"><a href="#魔数" class="headerlink" title="魔数"></a>魔数</h2><blockquote>
<p>很多文件格式都会规定满足该格式的文件必须以某几个固定字节开头，这几个字节主要起标识作用，叫作魔数（magic number）。例如 PDF 文件以 4 字节“%PDF”（0x25、0x50、0x44、0x46）开头，ZIP 文件以 2 字节“PK”（0x50、0x4B）开头。class 文件的魔数是“0xCAFEBABE”。<br>开头的四字节,起标识作用.Java 虚拟机规范规定，如果加载的 class 文件不符合要求的格式，Java 虚拟机实现就抛出<code>java.lang.ClassFormatError</code>异常。</p>
</blockquote>
<p>校验魔数使用的方法:<code>ClassFile#readAndCheckMagic()</code></p>
<h2 id="版本号"><a href="#版本号" class="headerlink" title="版本号"></a>版本号</h2><ul>
<li>次版本号(m):2 字节</li>
<li>主版本号(M):2 字节</li>
</ul>
<p>完整的版本号可以表示成“M.m”的形式。次版本号只在 J2SE 1.2 之前用过，从 1.2 开始基本上就没什么用了（都是 0）。主版本号在 J2SE 1.2 之前是 45，从 1.2 开始，每次有大的 Java 版本发布，都会加 1。 </p>
<p>校验版本使用的方法:<code>ClassFile#readAndCheckVersion()</code></p>
<h2 id="常量池"><a href="#常量池" class="headerlink" title="常量池"></a>常量池</h2><p>版本号之后是常量池，但是由于常量池比较复杂，所以放到<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-5-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B8%B8%E9%87%8F%E6%B1%A0/">手写JVM系列(5)-分析class文件-常量池</a>中介绍。</p>
<h2 id="访问标志"><a href="#访问标志" class="headerlink" title="访问标志"></a>访问标志</h2><p>在常量池之后,紧接着是两字节的访问标志（access_flags），这个标示用来识别<strong>类或者接口</strong>的访问信息，两字节供 16 位，目前只定义了 8 位，没有用到的一律用 0 来填充，以备以后的拓展使用。</p>
<table>
<thead>
<tr>
<th align="left">标志名称</th>
<th>标志值</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td align="left">ACC_PUBLIC</td>
<td>0x0001</td>
<td>是否为 public 类型</td>
</tr>
<tr>
<td align="left">ACC_FINAL</td>
<td>0x0010</td>
<td>是否被声明为 final，只有类可设置</td>
</tr>
<tr>
<td align="left">ACC_SUPER</td>
<td>0x0020</td>
<td>是否允许使用 invokespecial 字节码指令的新语义，JDK1.0.2 之后编译出来的这个标志都必须为 1</td>
</tr>
<tr>
<td align="left">ACC_INTERFACE</td>
<td>0x0200</td>
<td>标示这是一个接口</td>
</tr>
<tr>
<td align="left">ACC_ABSTRACT</td>
<td>0x0400</td>
<td>是否为 abstract 类型，对于接口或者抽象类来说，此标志为真，其他类值为假</td>
</tr>
<tr>
<td align="left">ACC_SYNTHETIC</td>
<td>0x1000</td>
<td>标志这个类并非由用户代码产生的</td>
</tr>
<tr>
<td align="left">ACC_ANNOTATION</td>
<td>0x2000</td>
<td>标志这是一个注解</td>
</tr>
<tr>
<td align="left">ACC_ENUM</td>
<td>0x4000</td>
<td>标志这是一个枚举</td>
</tr>
</tbody></table>
<h2 id="类索引"><a href="#类索引" class="headerlink" title="类索引"></a>类索引</h2><p>访问标志之后是 u2 类型的类索引数据，用于确定这个类的全限定名。该 u2 类型的索引值指向常量池中一个类型为 CONSTANT_Class_info 的类描述符常量,再通过 CONSTANT_Class_info 类型的常量中的索引值,可以找到定义在 CONSTANT_Utf8_info 类型的常量中的全限定名字符串。</p>
<p>类索引说白了就是一个指向常量池的索引值，那么直接用一个 int 值来表示即可。</p>
<h2 id="父类索引"><a href="#父类索引" class="headerlink" title="父类索引"></a>父类索引</h2><p>类索引之后是 u2 类型的父类索引数据，用于确定这个类的父类的全限定名。由于 Java 语言不允许多继承，所以其父类索引只有一个。除了 java.lang.Obect 之外,所有的 Java 类都有父类，所以除了 java.lang.Obect 的父类索引为 0，其余都不为 0。</p>
<p>该 u2 类型的索引值指向常量池中一个类型为 CONSTANT_Class_info 的类描述符常量,在通过 CONSTANT_Class_info 类型的常量中的索引值,可以找到定义在 CONSTANT_Utf8_info 类型的常量中的全限定名字符串。</p>
<p>同理，父类索引也是直接用一个 int 值来表示。</p>
<h2 id="接口索引集合"><a href="#接口索引集合" class="headerlink" title="接口索引集合"></a>接口索引集合</h2><p>父类索引之后是 u2 类型数据的接口索引集合。用来表述这个类实现了哪些接口。按照 implements 语句后面的接口顺序从前向后在接口索引集合中。</p>
<p>入口的第一项是 u2 类型的接口计数器，表示接口索引表的大小，如果该类没有实现接口，则计数器为 0，后面的接口索引表不占用任何字节。</p>
<p>因为有可能实现了多个接口，所以使用一个数组来盛放实习了接口在常量池中的索引值。</p>
<h2 id="字段表集合"><a href="#字段表集合" class="headerlink" title="字段表集合"></a>字段表集合</h2><p>接口索引集合之后是字段表集合。虚拟机规范给出的字段结构定义如下，字段表用来描述类或接口中声明的变量。包括静态变量和非静态变量。：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">field_info &#123;</span><br><span class="line">  u2 access_flags;		<span class="comment">//字段的访问修饰符</span></span><br><span class="line">  u2 name_index;		<span class="comment">//常量池索引，代表字段的简单名称</span></span><br><span class="line">  u2 descriptor_index;	<span class="comment">//常量池索引，代表字段描述符</span></span><br><span class="line">  u2 attributes_count;	<span class="comment">//字段的额外附加属性数量</span></span><br><span class="line">  attribute_info attributes[attributes_count];	<span class="comment">//字段的额外的附加属性</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>字段表中第一个字段 u2 是访问修饰符，这和前面讲的类访问符标志很相似，下表列举下字段的访问标志可选项：</p>
<table>
<thead>
<tr>
<th>标志名称</th>
<th>标志值</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>ACC_PUBLIC</td>
<td>0x0001</td>
<td>字段是否为 public</td>
</tr>
<tr>
<td>ACC_PRIVATE</td>
<td>0x0002</td>
<td>字段是否为 private</td>
</tr>
<tr>
<td>ACC_PROTECTED</td>
<td>0x0004</td>
<td>字段是否为 protected</td>
</tr>
<tr>
<td>ACC_STATIC</td>
<td>0x0008</td>
<td>字段是否为 static</td>
</tr>
<tr>
<td>ACC_FINAL</td>
<td>0x0010</td>
<td>字段是否为 final</td>
</tr>
<tr>
<td>ACC_VOLATILE</td>
<td>0x0040</td>
<td>字段是否为 volatile</td>
</tr>
<tr>
<td>ACC_TRANSIENT</td>
<td>0x0080</td>
<td>字段是否为 transient</td>
</tr>
<tr>
<td>ACC_SYNTHETIC</td>
<td>0x1000</td>
<td>字段是否由编译器自动产生</td>
</tr>
<tr>
<td>ACC_ENUM</td>
<td>0x4000</td>
<td>字段是否是 enum 类型</td>
</tr>
</tbody></table>
<p>在实际情况中访问标志的使用时有限制的，比如 ACC_PUBLIC、ACC_PRIVATE 和 ACC_PROTECTED 三个标志只能选其一，ACC_FINAL 和 ACC_VOLATILE 只能选其一等，这些都是由 Java 本身的语言规范所决定的。</p>
<p>随着 access_flags 标志后的两项索引值是 name_index 和 descriptor_index。他们都是对常量池的引用，分别代表着字段的名称和描述。</p>
<p>字段的简单名称：不含类型的字段名称。 （eg：int  i,其简单名称为 i）</p>
<p>字段的描述符：用来描述字段的数据类型。(eg: int i,其描述符为 I)</p>
<p>​                                    描述符标识字符含义:</p>
<p><img src="http://i.imgur.com/G01YtQJ.png" alt></p>
<p>对于数组类型，每一维度将使用一个前置的“[”字符来描述。如定义一个<code>String[][]</code>类型的二维数组，其描述符为：<code>[[Ljava/lang/String;</code></p>
<p>用描述符来描述方法时，按照先参数列表，后返回值的顺序描述，参数列表按照参数的严格顺序放在一组小括号“()”之内。</p>
<p>在 descriptor_index 之后跟随着一个 u2 类型的数据 len，描述后面一个长度为 len 的属性表数组，这个数组用于存储一些额外的信息，字段都可以在属性表中描述零至多项的额外信息。当然这个属性数组中保存的并不是真正的属性，而是属性表的索引。关于属性表，将在<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-6-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B1%9E%E6%80%A7%E8%A1%A8/">手写JVM系列(6)-分析class文件-属性表</a>中单独介绍。</p>
<p><strong>注：字段表集合中不会列出从超类或者父接口中继承而来的字段，但是有可能列出原来 Java 代码中不存在的字段，譬如在内部类中为了保持外部类的访问性，会自动添加一个指向外部类实例的字段。</strong></p>
<h2 id="方法表集合"><a href="#方法表集合" class="headerlink" title="方法表集合"></a>方法表集合</h2><p>字段表之后是方法表集合，和字段表集合的描述几乎是一样的（因此我在代码中对方法表和字段表使用同一个类 MemberInfo 来表示的），其结构如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">field_info &#123;</span><br><span class="line">  u2 access_flags;		<span class="comment">//方法的访问修饰符</span></span><br><span class="line">  u2 name_index;		<span class="comment">//常量池索引，代表方法的简单名称</span></span><br><span class="line">  u2 descriptor_index;	<span class="comment">//常量池索引，代表方法描述符</span></span><br><span class="line">  u2 attributes_count;	<span class="comment">//方法的额外附加属性数量</span></span><br><span class="line">  attribute_info attributes[attributes_count];	<span class="comment">//方法的额外的附加属性</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方法表的第一个字段是访问修饰符，和字段表访问修饰符类似，不同的是：因为 volatile 和 transient 关键字不能修饰方法，所以方法表的访问标志中没有这这两项，但是添加了 synchronized，native，strictfp，abstract 等可用来修饰方法的关键字，具体如下：</p>
<table>
<thead>
<tr>
<th>标志名称</th>
<th>标志值</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>ACC_PUBLIC</td>
<td>0x0001</td>
<td>方法是否为 public</td>
</tr>
<tr>
<td>ACC_PRIVATE</td>
<td>0x0002</td>
<td>方法是否为 private</td>
</tr>
<tr>
<td>ACC_PROTECTED</td>
<td>0x0004</td>
<td>方法是否为 protected</td>
</tr>
<tr>
<td>ACC_STATIC</td>
<td>0x0008</td>
<td>方法是否为 static</td>
</tr>
<tr>
<td>ACC_FINAL</td>
<td>0x0010</td>
<td>方法是否为 final</td>
</tr>
<tr>
<td>ACC_SYNCHRONIZED</td>
<td>0x0020</td>
<td>方法是否为 synchronized</td>
</tr>
<tr>
<td>ACC_BRIDGE</td>
<td>0x0040</td>
<td>方法是否是由编译器产生的桥接方法</td>
</tr>
<tr>
<td>ACC_VARARGS</td>
<td>0x0080</td>
<td>方法是否接受不定参数</td>
</tr>
<tr>
<td>ACC_NAVIVE</td>
<td>0x0100</td>
<td>方法是否为 native</td>
</tr>
<tr>
<td>ACC_ABSTRACT</td>
<td>0x0400</td>
<td>方法是否为 abstract</td>
</tr>
<tr>
<td>ACC_STRICTFP</td>
<td>0x0800</td>
<td>方法是否为 strictfp</td>
</tr>
<tr>
<td>ACC_SYNTHETIC</td>
<td>0x1000</td>
<td>方法是否由编译器自动产生</td>
</tr>
</tbody></table>
<p>随着 access_flags 标志后的两项索引值是 name_index 和 descriptor_index。他们都是对常量池的引用，分别代表着方法的名称和描述。</p>
<p>方法的简单名称：不含类型和返回值的方法名称。</p>
<p>方法的描述符：描述方法的参数列表（数量，类型，顺序）和返回值。</p>
<p>以  eg：int func (int i，String s) 为例子,其简单名称为 func，方法描述符为：可参照上面的描述符标识字符含义图。</p>
<p>方法的简单名称：func</p>
<p>方法的描述符：(ILjava/lang/String)I</p>
<p>在 descriptor_index 之后跟随着一个 u2 类型的数据 len，描述后面一个长度为 len 的属性表数组，这个数组用于存储一些额外的信息，方法可以在属性表中描述零至多项的额外信息。和字段不同的是，字段只需要一个变量名和对应值就可以了，但是方法内部是包含代码的，这段代码在字节码中是如何表示的呢？答案是放在了方法属性表中的 Code 属性中，和字段表一样，方法表中的属性数组中并不保存真正的属性，而是保存的属性表的索引，关于属性表，将在<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-6-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B1%9E%E6%80%A7%E8%A1%A8/">手写JVM系列(6)-分析class文件-属性表</a>中单独介绍。</p>
<p><strong>注意：如果父类方法在子类中没有被重写，方法表集合中就不会出现来自父类的信息。和字段表类似的是，方法表中可能会出现编译器会自动添加的方法，最典型的就是：类构造器<code>&lt;clinit&gt;</code>和实例构造器<code>&lt;init&gt;</code></strong></p>
<p>关于方法的重载</p>
<p> 重载一个方法，除了要与原方法具有相同的简单名称之外，还要求必须拥有一个与原方法不同的特征签名。特征签名就是一个方法中各个参数在常量池中的字段符号引用集合，而返回值不会包含在特征签名中。但是如果两个方法具有相同的名称和特征签名，只是返回值不同，那么也可以合法共存于同一个 Class 文件中的。但是编译器是会阻止这一行为的，如果两个方法仅仅是返回值不同，编译器会直接报错。所以只能通过字节注入的方式，实现返回值不同的两个方法。</p>
<h2 id="属性表"><a href="#属性表" class="headerlink" title="属性表"></a>属性表</h2><p>方法表集合之后是属性表，但是由于属性表比较复杂，所以放到<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-6-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B1%9E%E6%80%A7%E8%A1%A8/">手写JVM系列(6)-分析class文件-属性表</a>中介绍。</p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/08/手写JVM系列-3-搜索class文件/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/05/08/手写JVM系列-3-搜索class文件/" itemprop="url">手写JVM系列(3)-搜索class文件</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-08T15:01:12+08:00">
                2017-05-08
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,477
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">






          <blockquote>
<p>本节的目的是根据<code>-cp</code>命令指定的class路径以及后面的<code>ClassName</code>,找到对应的class文件,然后简单的打印出该 class 文件的字节码.完整源码<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">classpath包中</a></p>
</blockquote>
          <!--noindex-->
          <div class="post-button text-center">
            <a class="btn" href="/2017/05/08/手写JVM系列-3-搜索class文件/#more" rel="contents">
              阅读全文 &raquo;
            </a>
          </div>
          <!--/noindex-->


    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>



  </section>


  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/9/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/9/">9</a><span class="page-number current">10</span><a class="page-number" href="/page/11/">11</a><span class="space">&hellip;</span><a class="page-number" href="/page/13/">13</a><a class="extend next" rel="next" href="/page/11/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>





        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">





      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>





    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>











  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
